How to check if a variable is an integer? [closed]

Posted by FyrePlanet on Game Development See other posts from Game Development or by FyrePlanet
Published on 2013-05-27T14:54:39Z Indexed on 2013/06/26 16:30 UTC
Read the original article Hit count: 106

Filed under:
|

I'm going through my C++ book and have currently made a working Guess The Number game.

The game generates a random number based on current time, has the user input their guess, and then tells them whether it was too high, too low, or the correct number.

The game functions fine if you enter a number, but returns 'Too High' if you enter something that is not a number (such as a letter or punctuation). Not only does it return 'too high', but it also continually returns it.

I was wondering what I could do to check if the guess, as input by the user, is an integer and if it is not, to return 'Not a number. Guess again.'

Here is the code.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0)); // seed the random number generator
    int theNumber = rand() % 100 + 1; // random number between 1 and 100
    int tries = 0, guess;

    cout << "\tWelcome to Guess My Number!\n\n";

    do
    {
        cout << "Enter a guess: ";
        cin >> guess;
        ++tries;

        if (guess > theNumber)
                cout << "Too high!\n\n";

        if (guess < theNumber)
                cout << "Too low!\n\n";

    } while (guess != theNumber);

    cout << "\nThat's it! You got it in " << tries << " guesses!\n";
    cout << "\nPress Enter to exit.\n";

    cin.ignore(cin.rdbuf()->in_avail() + 1);
    return 0;
}

© Game Development or respective owner

Related posts about c++

Related posts about c++11